package com.kindergarten.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kindergarten.utils.DataResults;
import com.kindergarten.utils.ResultCode;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *  认证失败处理器
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    /**
     * 认证失败处理逻辑
     * @param request
     * @param response
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        //  响应一段JSON UTF-8编码
        response.setContentType("application/json;charset=utf-8");
        DataResults dataResults=DataResults.success(ResultCode.LOGIN_FAIL); //9002
        // 人工转JSON
        String jsonResult = new ObjectMapper().writeValueAsString(dataResults);
        response.getWriter().write(jsonResult);
    }
}
